package com.jeff.grailsstudy

import groovy.xml.MarkupBuilder
import grails.converters.*

class AuthorController {
    
    def beforeInterceptor = {
//        println "Tracing action: ${actionUri}"
    }

    def index() { }
    
    def aHtml() {
        render {
            for (i in 1..3) {
                div(id:i, "I am Div_$i")
            }
        }
    }
    
    def aXml() {
//        render(text: "<parent><child>child1</child><child>child2</child></parent>", 
//            contentType: "text/xml", encoding: "UTF-8")
        render(contentType: "text/xml", encoding: "UTF-8") {
            def authors = Author.list()
            Authors(size: authors.size()) {
                for (author in authors) {
                    Author(id: author.id, name: author.name, age: author.age) {
                        author.nickName
                    }
                }
            }
        }
    }
    
    def aJson() {
        render(contentType: "text/json", encoding: "UTF") {
            def authors = Author.list()
            Authors(size: authors.size(), authorList: array {
                    for (author in authors) {
                        Author(id: author.id, name: author.name, age: author.age)
                    }
            })
        }
    }
    
    def bJson() {
        render Author.list() as JSON
    }
    
    def aBuiltHtml() {
        def writer = new StringWriter()
        new MarkupBuilder(writer).html {
            header {
                title 'Th title'
            }
            body {
                h1 'Hello'
                form {
                    
                }
            }
        }
        
        render writer.toString()
    }
    
    def chainModel() {
        forward(action: "chain1")
    }
    def chain1() {//use "chain()", the browser URL will change accordingly
        chain(action: "chain2", model: ["One": 1])
    }
    def chain2() {
        chain(action: "chainLast", model: ["Two": 2])
    }
    def chainLast() {
//        print chainModel
        
        render {
            for (model in chainModel) {
                div(id: model.value, model.key)
            }
            div(id: "home") {
                a(href: "chainModel") {
                    h3 "Again!"
                }
            }
        }
    }
    
    def show() {
        log.info "** executing $actionUri"
        [authorInstance: Author.list().first(), allBooks: Book.list()]
    }
    
    def update() {
        def author = Author.get(params.id)
        if (author == null) {
            //handle when domain obj not exists
            flash.message = "Domain not found!"
        }
        if (author.version > params.version) {
            //handle when optimistic lock hit
            flash.message = "Domain is dirty! Please refresh before edit"
        }
        
        params.books.each {
            println "** $it"
        }
//        author.properties = params
        bindData(author, params, [only: 'books'])
        author.save(flush: true)
        
        redirect (action: "show")
    }
    
    def upload() {
        withForm {
            def file = request.getFile("myFile")
            println("** File is Empty: ${file.empty}")
            if (file.empty) {
                flash.message = "File cannot be empty"
                render(view: "showUploaded", model: showUploaded())
                return
            }

            file.transferTo(new File("/Users/winniewang/Documents/grails-io-pool/uploaded/${file.getName()}_${System.currentTimeMillis()}.txt"))
    //        response.sendError(200, 'Done')
            redirect(action: "showUploaded")
        }.invalidToken {
//            flash.message = "Please don't submit so many times."
            redirect(action: "showUploaded")
        }
        
    }
    
    def showUploaded() {
        def uploadFolder = new File("/Users/winniewang/Documents/grails-io-pool/uploaded")
        def allFiles = []
        uploadFolder.eachFile {
//            println "** file: $it"
            if (it.name[-4..-1].equals(".txt")) {
                allFiles.add(it)
            }
        }
        
        [uploadedFileList: allFiles]
    }
    
    def asyncCall() {
        def ctx = startAsync()
        def startTime = System.currentTimeMillis()
        ctx.start {
//            render "Ctx Started! @${System.currentTimeMillis() - startTime}"
            System.sleep(1000)
            render "Ctx Started! @${System.currentTimeMillis() - startTime}<br/>"
            System.sleep(2000)
            render "Ctx Completed! @${System.currentTimeMillis() - startTime}<br/>"
            ctx.complete()
        }
        render {
            div {
                h3 "Before Async Response @${System.currentTimeMillis() - startTime}"
            }
        }
//        render (view: "show")
    }
    
    def templateView() {
        def author = Author.get(1)
        [author: author]
    }
}
